package com.szc.demo01.controller;

import com.szc.demo01.controller.base.BaseController;
import com.szc.demo01.pojo.Dept;
import com.szc.demo01.pojo.Emp;
import com.szc.demo01.pojo.User;
import com.szc.demo01.pojo.dto.UserDto;
import com.szc.demo01.service.DeptService;
import com.szc.demo01.service.EmpService;
import com.szc.demo01.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import javax.annotation.Resource;

/**
 * 用户管理感知器
 */
@Controller
public class UserEmpController extends BaseController {

    @Resource
    UserService userService;

    @Resource
    EmpService empService;

    @Resource
    DeptService deptService;

    /**
     *
     */
    @GetMapping("/to_showUser")
    public String editableTable(Model model){
        //根据session的用户id查出用户的所有信息
        long userId = getUser().getId();
        User user = userService.getById(userId);
        Emp emp = empService.getById(userId);
        Dept dept = deptService.getById(emp.getDeptno());
        UserDto userDto = new UserDto(user, emp, dept);

        model.addAttribute("userDto",userDto);
        return "table/showUser_table";
    }

    /**
     * 编辑个人信息
     */
    @GetMapping("/toEditable")
    public String toEditable(Model model){
        //根据session的用户id查出用户的所有信息
        long userId = getUser().getId();
        User user = userService.getById(userId);
        Emp emp = empService.getById(userId);
        Dept dept = deptService.getById(emp.getDeptno());
        UserDto userDto = new UserDto(user, emp, dept);

        model.addAttribute("userDto",userDto);
        return "table/editable_table";
    }

    /**
     * 保存自己的信息
     */
    @PostMapping("/editable")
    public String editable(UserDto userDto){
        User user = userService.getById(userDto.getId());
        user.setUsername(userDto.getUsername());
        user.setEmail(userDto.getEmail());
        user.setTel(userDto.getTel());
        user.setAddress(userDto.getAddress());
        userService.updateById(user);
        return "table/showUser_table";
    }
}
